/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.liangjun.baselinetreatment.service.impl;

import me.liangjun.baselinetreatment.domain.*;
import me.liangjun.baselinetreatment.repository.*;
import me.liangjun.baselinetreatment.service.dto.BaseLineTreatmentFDto;
import me.liangjun.baselinetreatment.service.dto.ImmunosuppressantDto;
import me.liangjun.baselinetreatment.service.mapstruct.*;
import me.liangjun.baselinetreatmentdetails.domain.BaselineTreatmentDetails;
import me.liangjun.baselinetreatmentdetails.repository.BaselineTreatmentDetailsRepository;
import me.liangjun.baselinetreatmentdetails.service.dto.BaselineTreatmentDetailsDto;
import me.liangjun.baselinetreatmentdetails.service.mapstruct.BaselineTreatmentDetailsMapper;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.liangjun.baselinetreatment.service.BaselineTreatmentService;
import me.liangjun.baselinetreatment.service.dto.BaselineTreatmentDto;
import me.liangjun.baselinetreatment.service.dto.BaselineTreatmentQueryCriteria;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;

import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;

/**
 * @author wei
 * @website https://el-admin.vip
 * @description 服务实现
 * @date 2021-10-19
 **/
@Service
@RequiredArgsConstructor
public class BaselineTreatmentServiceImpl implements BaselineTreatmentService {

    private final BaselineTreatmentRepository baselineTreatmentRepository;
    private final MgImmuneTreatmentRepository mgImmuneTreatmentRepository;
    private final OtherTreatmentRepository otherTreatmentRepository;
    private final ThymicSurgeryHistoryRepository thymicSurgeryHistoryRepository;
    private final BaselineTreatmentDetailsRepository baselineTreatmentDetailsRepository;
    private final ImmunosuppressantRepository immunosuppressantRepository;
    private final BaselineTreatmentMapper baselineTreatmentMapper;
    private final MgImmuneTreatmentMapper mgImmuneTreatmentMapper;
    private final OtherTreatmentMapper otherTreatmentMapper;
    private final ThymicSurgeryHistoryMapper thymicSurgeryHistoryMapper;
    private final BaselineTreatmentDetailsMapper baselineTreatmentDetailsMapper;
    private final ImmunosuppressantMapper immunosuppressantMapper;


    @Override
    public Map<String, Object> queryAll(BaselineTreatmentQueryCriteria criteria, Pageable pageable) {
        Page<BaselineTreatment> page = baselineTreatmentRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        return PageUtil.toPage(page.map(baselineTreatmentMapper::toDto));
    }

    @Override
    public List<BaselineTreatmentDto> queryAll(BaselineTreatmentQueryCriteria criteria) {
        return baselineTreatmentMapper.toDto(baselineTreatmentRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Override
    @Transactional
    public BaselineTreatmentDto findById(Long id) {
        BaselineTreatment baselineTreatment = baselineTreatmentRepository.findById(id).orElseGet(BaselineTreatment::new);
        ValidationUtil.isNull(baselineTreatment.getId(), "BaselineTreatment", "id", id);
        return baselineTreatmentMapper.toDto(baselineTreatment);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseLineTreatmentFDto create(BaseLineTreatmentFDto resources) {
        BaselineTreatment baselineTreatment = baselineTreatmentMapper.toEntity(resources.getBaselineTreatment());
        BaselineTreatment baselineTreatmentd = baselineTreatmentRepository.findByPid(baselineTreatment.getPId());
        if (baselineTreatmentd != null) {
            baselineTreatmentd.copy(baselineTreatment);
            baselineTreatmentRepository.save(baselineTreatmentd);
        }else {
            baselineTreatmentRepository.save(baselineTreatment);
        }

        if (resources.getBaselineTreatment().getOtherTreatment() == 1) {
            OtherTreatment otherTreatment = otherTreatmentMapper.toEntity(resources.getOtherTreatment());
            OtherTreatment otherTreatmentd = otherTreatmentRepository.findByPid(otherTreatment.getPId());
            if (otherTreatmentd != null) {
                otherTreatmentd.copy(otherTreatment);
                otherTreatmentRepository.save(otherTreatmentd);
            }else {
                otherTreatmentRepository.save(otherTreatment);
            }
        }
        if (resources.getBaselineTreatment().getThymicSurgeryTreatment() == 1) {
            ThymicSurgeryHistory thymicSurgeryHistory = thymicSurgeryHistoryMapper.toEntity(resources.getThymicSurgeryHistory());
            ThymicSurgeryHistory thymicSurgeryHistoryd = thymicSurgeryHistoryRepository.findByPid(thymicSurgeryHistory.getPId());
            if (thymicSurgeryHistoryd != null) {
                thymicSurgeryHistoryd.copy(thymicSurgeryHistory);
                thymicSurgeryHistoryRepository.save(thymicSurgeryHistoryd);
            }else {
                thymicSurgeryHistoryRepository.save(thymicSurgeryHistory);
            }
            List<String> immunosuppressive = resources.getThymicSurgeryHistory().getImmunosuppressive();
            for (String s : immunosuppressive) {
                List<ImmunosuppressantDto> immunosuppressantDtos = resources.getImmunosuppressive();
                for (ImmunosuppressantDto immunosuppressantDto : immunosuppressantDtos) {
                    if (immunosuppressantDto.getDName().equals(s)) {
                        Immunosuppressant immunosuppressant = immunosuppressantMapper.toEntity(immunosuppressantDto);
                        Immunosuppressant immunosuppressantd = immunosuppressantRepository.findOne(immunosuppressant.getPId(), immunosuppressant.getDName());
                        if (immunosuppressantd != null) {
                            immunosuppressantd.copy(immunosuppressant);
                            immunosuppressantRepository.save(immunosuppressantd);
                        }else {
                            immunosuppressantRepository.save(immunosuppressant);
                        }
                    }
                }
            }
        }
        if (resources.getBaselineTreatment().getMgImmuneTreatment() == 1) {
            MgImmuneTreatment mgImmuneTreatment = mgImmuneTreatmentMapper.toEntity(resources.getMgImmuneTreatment());
            MgImmuneTreatment mgImmuneTreatmentd = mgImmuneTreatmentRepository.findByPid(mgImmuneTreatment.getPId());
            if (mgImmuneTreatmentd != null) {
                mgImmuneTreatmentd.copy(mgImmuneTreatment);
                mgImmuneTreatmentRepository.save(mgImmuneTreatmentd);
            }else {
                mgImmuneTreatmentRepository.save(mgImmuneTreatment);
            }
        }
        List<String> mgDrugTreatment = resources.getBaselineTreatment().getMgDrugTreatment();
        for (String s : mgDrugTreatment) {
            if (s.isEmpty()) {
                continue;
            }
            List<BaselineTreatmentDetailsDto> drug = resources.getDrug();
            for (BaselineTreatmentDetailsDto dto : drug) {
                if (dto.getDId() == Long.valueOf(s)) {
                    BaselineTreatmentDetails baselineTreatmentDetails = baselineTreatmentDetailsMapper.toEntity(dto);
                    BaselineTreatmentDetails baselineTreatmentDetailsd = baselineTreatmentDetailsRepository.finOne(baselineTreatmentDetails.getPId(), baselineTreatmentDetails.getDId());
                    if (baselineTreatmentDetailsd != null) {
                        baselineTreatmentDetailsd.copy(baselineTreatmentDetails);
                        baselineTreatmentDetailsRepository.save(baselineTreatmentDetailsd);
                    }else {
                        baselineTreatmentDetailsRepository.save(baselineTreatmentDetails);
                    }
                }
            }
        }
        return resources;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(BaselineTreatment resources) {
        BaselineTreatment baselineTreatment = baselineTreatmentRepository.findById(resources.getId()).orElseGet(BaselineTreatment::new);
        ValidationUtil.isNull(baselineTreatment.getId(), "BaselineTreatment", "id", resources.getId());
        baselineTreatment.copy(resources);
        baselineTreatmentRepository.save(baselineTreatment);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            baselineTreatmentRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<BaselineTreatmentDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (BaselineTreatmentDto baselineTreatment : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("pID", baselineTreatment.getPId());
            map.put("其他治疗", baselineTreatment.getOtherTreatment());
            map.put("MG药物治疗", baselineTreatment.getMgDrugTreatment());
            map.put("有无MG免疫治疗", baselineTreatment.getMgImmuneTreatment());
            map.put("有无胸腺手术治疗", baselineTreatment.getThymicSurgeryTreatment());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public BaselineTreatmentDto findByPid(Long pid) {
        return baselineTreatmentMapper.toDto(baselineTreatmentRepository.findByPid(pid));
    }
}